import Express from 'express'
import { MovieServices } from '../services/MovieServices';
import { ResponseHelper } from './ResponseHelper';
import { SearchCondition } from '../entities/SearchConditions';
const router = Express.Router();

router.get('/:id', async (req, res) => {
    try {
        const movieId = req.params.id
        const movie = await MovieServices.findById(movieId)
        // 响应：服务器的接口响应格式,往往是一种标准格式
        ResponseHelper.sendData(movie, res)
    } catch {
        ResponseHelper.sendError('id不存在', res)
    }
})

router.get('/', async (req, res) => {
    try {
        const result = await MovieServices.find((req.query as unknown) as SearchCondition)
        // 响应：服务器的接口响应格式,往往是一种标准格式
        ResponseHelper.sendPageData(result, res)
    } catch {
        ResponseHelper.sendError('服务器内部错误', res)
    }
})

router.post("/", async (req, res) => {
    const result = await MovieServices.addMovies(req.body)
    if (Array.isArray(result)) {
        ResponseHelper.sendError(result, res)
    } else {
        ResponseHelper.sendData(result, res)
    }
})

router.put('/:id', async (req, res) => {
    try {
        const errors = await MovieServices.editMovies(req.params.id, req.body)
        if (errors.length > 0) {
            ResponseHelper.sendError(errors, res)
        } else {
            ResponseHelper.sendData(true, res)
        }
    } catch {
        ResponseHelper.sendError('id不存在', res)
    }
})

router.delete('/:id', async (req, res) => {
    try {
        MovieServices.deleteMovie(req.params.id)
    } catch {
        ResponseHelper.sendError('id不存在', res)
    }
})

export default router;